'use client'
import React, { Suspense } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { Button } from '@/components/ui/button';
import ArticleEditor from '@/components/ArticleEditor';
import { Article } from '@/types/article';

const NewArticlePageContent = () => {
  const router = useRouter();
  const searchParams = useSearchParams();
  
  // 从URL参数获取文章ID
  const articleIdParam = searchParams.get('id');
  const editParam = searchParams.get('edit'); // 支持profile页面使用的edit参数
  
  // 确定是否为编辑模式，以及文章ID
  const articleId = articleIdParam ? parseInt(articleIdParam) : 
                   editParam ? parseInt(editParam) : undefined;
  
  // 处理文章保存成功后的导航逻辑
  const handleSaveSuccess = (article: Article | null) => {
    if (article === null) {
      // 用户点击了取消按钮
      router.back();
    } else if (articleId) {
      // 编辑模式保存成功，导航回个人中心的文章列表
      setTimeout(() => {
        router.push('/profile?tab=articles');
      }, 1500);
    } else {
      // 创建模式保存成功，导航回首页
      setTimeout(() => {
        router.push('/');
      }, 1500);
    }
  };

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="max-w-3xl mx-auto">
        <div className="flex justify-between items-center mb-6">
          <h1 className="text-3xl font-bold text-foreground">
            {articleId ? '编辑文章' : '发布新文章'}
          </h1>
          <Button
            variant="ghost"
            onClick={() => router.back()}
            size="icon"
          >
            返回
          </Button>
        </div>
        
        {/* 使用可重用的ArticleEditor组件 */}
        <ArticleEditor 
          articleId={articleId} 
          onSaveSuccess={handleSaveSuccess} 
        />
      </div>
    </div>
  );
};

const NewArticlePage = () => {
  return (
    <Suspense fallback={<div>加载中...</div>}>
      <NewArticlePageContent />
    </Suspense>
  );
};

export default NewArticlePage;
